#include "../master.h"
#include "../comfunct/comfunct.h"
#include "update.h"
#include "resource.h"

extern bool bStop;
extern HFONT hfDefault, hfBold;

LRESULT CALLBACK UpdateProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{    
    static PARAMS params = {0};
    static HANDLE hThread = NULL;
	static DWORD dwThreadId = 0;
	const HBRUSH hbrEditBrush = GetSysColorBrush(COLOR_3DLIGHT);
	static HBRUSH hbrBackBrush = NULL;
    
    switch(msg)
    {        
        case WM_COMMAND:
        {
             switch(LOWORD(wParam))
             {
                  case DLG_STOP_BUTTON:
                  {
                       bStop = true;
                  }
                  break;
             }
        }
        break;
        case WM_CREATE:
             {
				 CREATESTRUCT* pcs = (CREATESTRUCT*)lParam;
				 hbrBackBrush = GetSysColorBrush(COLOR_WINDOW);

                 params.hwnd = hwnd;
                 ControlCreate(hwnd);
                 params.hInitConnect = ConnectHandle(TEXT("AudioPlayer"));
				 if(params.hInitConnect == NULL)
				 {
					 ErrorInfo();
					 ErrorMessage(GetLocalText(93));
					 return TRUE;
				 }
                 params.iFileVersion = *(int*)pcs->lpCreateParams;
                 hThread = CreateThread(NULL, 0, ThreadFunc, &params, 0, &dwThreadId);
             }
        break;
        case WM_CLOSE:
             {
                 if(bStop == false)
                 {
                     bStop = true; /* If the user uses the 'X' button to close the window
                                      this stops the downloading and subsequent installation
                                      taking place */
                 }
                 DeleteObject(hfDefault);
                 DeleteObject(hfBold);
				 DestroyWindow(hwnd);
				 CloseHandle(hThread);
             }
        break;
		case WM_CTLCOLORSTATIC:
        case WM_CTLCOLORBTN:
        {
             HDC hdcStatic = (HDC)wParam;
             SetBkMode(hdcStatic, TRANSPARENT);
             return (LRESULT)hbrBackBrush;
        }
        break;
        case WM_CTLCOLOREDIT:
        {
             HDC hdcStatic = (HDC)wParam;
             SetBkMode(hdcStatic, TRANSPARENT);
             return (LRESULT)hbrEditBrush;
        }
        break;
        case WM_PAINT:
		{
			 HDC hdc = NULL;
			 PAINTSTRUCT ps = {0};
			 RECT rc = {0};

			 GetClientRect(hwnd, &rc);

			 hdc = BeginPaint(hwnd, &ps);
			 FillRect(hdc, &rc, hbrBackBrush);
			 EndPaint(hwnd, &ps);
		}
		break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}
